<template>
  <div class="kxz-home--adminer">
    <section class="container">
      <h2 class="title">
        <i class="icon icon-pb"></i>今天排班</h2>
      <table class="content--pb">
        <tr>
          <!-- <th v-if="cuUserType === 2" colspan="2">{{cuJRPBTitle}}</th> -->
          <!-- <template v-else-if="cuUserType === 1"> -->
          <th v-for="(item,index) in cuJRPBTitle" :key="index" colspan="2">{{item}}</th>
        </tr>
        <tr>
          <td v-for="(item,index) in cuOrderTitles" :key="index" colspan="2" v-text="item"></td>
        </tr>
        <tr>
          <td v-if="cuJRPB.length === 0" colspan="2">
            暂无记录
          </td>
          <template v-else>
            <td v-for="(subGroup, sIndex) in cuJRPB" :key="sIndex" colspan="2">
              <table class="subOrderInDay" :class="subGroup.length > 0? 'unemptyArr' : ''">
                <tr>
                  <td v-if="subGroup.length === 0" v-text="'暂无记录'"></td>
                  <td v-for="(ssItem,ssIndex) in subGroup" :key="ssIndex" v-text="ssItem.kfName || '无名氏'"></td>
                </tr>
              </table>
            </td>
          </template>
        </tr>
      </table>
    </section>
    <section class="container">
      <h2 class="title">
        <i class="icon icon-pb"></i>实时监控</h2>
        <el-table
          :data="rt.tableData"
          style="width: 100%">
          <el-table-column
            v-for="item in rt.titleList"
            :key="item.label"
            :prop="item.prop"
            :label="item.label"
          >
          </el-table-column>
        </el-table>
    </section>
    <section class="container">
      <p class="zrjk__top">
          <el-button
            v-for="item in admin.group"
            :key="item.value"
            :class="admin.selGid === item.value ?'active' : ''"
            @click="handleChangeGroup(item.value)"
            v-text="item.label"
          >
          </el-button>
      </p>
      <h2 class="title">
        <i class="icon icon-th"></i>昨日通话监控</h2>
      <div class="content--zr scrollContainer">
        <table>
          <tr>
            <th></th>
            <th>{{cuTitles}}</th>
          </tr>
          <tr>
            <td>
              <ul>
                <li>名字</li>
                <li>在线时间（h）</li>
                <li>通话量</li>
                <li>平均时长（m）</li>
                <li>在线客户解答量</li>
                <li>平均解决时长（m）</li>
                <li>满意度</li>
              </ul>
            </td>
            <template v-for="(subArr, subKey) in cuZRTH">
              <td v-if="subArr.length > 0" :key="subKey">
                <div class="fbox" v-if="subArr.length > 0">
                  <ul v-for="(item,index) in subArr" :key="index">
                    <li>{{item.UserName}}</li>
                    <li>{{item.zxsj}}</li>
                    <li>{{item.zcount_y}}</li>
                    <li>{{item.zcount_zscpjyjt}}</li>
                    <li>{{item.zcount_callin_y}}</li>
                    <li>{{item.zcount_callin_zscpj}}</li>
                    <li>
                      <span class="check" @click="handleOpenMyd(item.adminid,item.UserName)">查看</span>
                    </li>
                  </ul>
                </div>
                <div class="empty" v-else>
                  暂无记录
                </div>
              </td>
            </template>
            <td v-if="isEmpty(cuZRTH)">
              暂无记录
            </td>
          </tr>
        </table>
      </div>
    </section>
    <myd :PkfName="kfName" :PsDialog="sDialog" :PmydData="mydData" @oncloseDialog="revCloseDialog"></myd>
  </div>
</template>

<script>
import Myd from '../../../components/myd'

export default {
  name: 'zj',
  data() {
    const {power} = this.$store.getters.getUserInfo
    return {
      // 实时监控
      rt:{
        tableData:[],
        titleList:[
          {
            prop:'UserName',
            label:'组别',
          },
          {
            prop:'zcount',
            label:'总通话量',
          },
          {
            prop:'zcount_callin',
            label:'呼入数',
          },
          {
            prop:'zcount_callout',
            label:'接通数',
          },
          // 等接口
          // {
          //   prop:'kf',
          //   label:'登录坐席数',
          // },
          //
          {
            prop:'onlines',
            label:'在线坐席数',
          },
          {
            prop:'frees',
            label:'空闲中',
          },
          {
            prop:'calls',
            label:'通话中',
          },
          {
            prop:'busys',
            label:'暂离数',
          },
          {
            prop:'exits',
            label:'离线数',
          },
          // 等接口
          // {
          //   prop:'kf',
          //   label:'排队客户数',
          // },
          //
          {
            prop:'jtl',
            label:'接通率',
          },
        ],
      },
      alltel:[],
      //
      power,
      localGroupStr: ['YWZ', 'DYZ', 'HFZ'],  // 根据Str限定组顺序
      localGroupNum: {                       // 根据Num限定组顺序
        104: [],
        100: [],
        112: [],
      },
      jrpb: null,   // 今日排班
      zrth: null,   // 昨日通话
      kfName: '',
      sDialog: false,
      mydData: {},
      admin:{
        selGid:104,
        group:[    // 只有admin登录才会出现
          {label:'业务组',value:104},
          {label:'答疑组',value:100},
          {label:'回访组',value:112},
        ]
      }
    }
  },
  components: {
    Myd
  },
  computed: {
    cuOrderTitles() {
      // const { power,userGroup } = this.$store.getters.getUserInfo
      const configOrderTitle = ['值班']
      return [...configOrderTitle, ...configOrderTitle, ...configOrderTitle]
    },
    cuJRPBTitle(){  // 质检组title部分
      return ['业务组', '答疑组', '回访组']
    },
    cuTitles() {
      const groups = this.$store.getters.getGroup
      return groups[this.admin.selGid.toString()]
    },
    cuUserType() {
      return this.$store.getters.getUserInfo.power
    },
    cuJRPB() {
      const orderInDay = this.jrpb
      const localGroupStr = this.localGroupStr
      let tmpa = []
      if (orderInDay && Object.keys(orderInDay).length > 0) {
        localGroupStr.forEach(item => {
            tmpa.push(orderInDay[item])
        })
        tmpa.forEach((tItem, tIndex) => {
          const ta = []
          for(let k in tItem){
            /**
             * 更改需求：只要晚班，并把晚班改成值班
             */
            if(k.includes('NigKefu')){
              ta.push(tItem[k])
            }
          }
          tmpa = [...tmpa, ...ta]
          tmpa.splice(0, 1)
        })
      }
      return tmpa
    },
    cuZRTH() {
      // const tmpo = Object.assign({},this.localGroupNum)
      const tmpo = {                       // 根据Num限定组顺序
        104: [],
        100: [],
        112: []
      }
      const zrth = this.zrth
      if (zrth && zrth.length > 0) {
        zrth.forEach(item => {
          tmpo[item.UserGroupId].push(item)
        })
      }
      return tmpo
    },
    // 实时监控数据
    cuSeats(){   // 获取通话状态信息
      return this.$store.getters.seats
    },
    cuQueues(){  // 获取排队客户信息
      return this.$store.getters.queues
    },
    cuCalls(){   // 获取通话信息
      return this.$store.getters.calls
    },
    //
  },
  watch:{
    cuSeats(){
      this.sjjkData()
    },
    cuQueues(){
      this.sjjkData()
    },
    cuCalls(){
      this.sjjkData()
    },
    cuGetGroup(){
      return this.$store.getters.getGroup
    },
  },
  mounted() {
    let userGroupId = this.admin.selGid
    // 获取今日排班信息
    this.getJRPB()
    // 获取昨日通话监控
    this.getZRTH(userGroupId)
    // 获取实时监控
    this.getSJJK()

    //获取所有分机号
    this.getAllTel()
  },
  methods: {
    handleOpenMyd(adminid, userName) {
      this.sDialog = true
      this.kfName = userName
      this.getMyd(adminid)
    },
    handleChangeGroup(gid){
      this.admin.selGid = gid
      this.getZRTH(gid)
    },
    revCloseDialog() {
      this.sDialog = false
    },
    isEmpty(cuZRTH) {
      const userType = this.cuUserType
      const empty3Arr = this._is3EmptyArr(cuZRTH)
      return userType === 2 && empty3Arr
    },
    sjjkData(){
      const seats = this.cuSeats
      const queues = this.cuQueues
      const calls = this.cuCalls
      const getGroup = this.getGroup
      const alltel = this.alltel
      /**
       * onlines 在线数
       * frees 空闲数
       * calls 通话数
       * busys 暂离数
       * exits 离线数
       * queues 排队数
      */
      const data = {
        '业务组':{
          onlines:0,
          frees:0,
          calls:0,
          busys:0,
          exits:0,
          // queues:0,
        },
        '答疑组':{
          onlines:0,
          frees:0,
          calls:0,
          busys:0,
          exits:0,
          // queues:0,
        },
        '回访组':{
          onlines:0,
          frees:0,
          calls:0,
          busys:0,
          exits:0,
          // queues:0,
        },
      }
      // 排队处理
      // if(queues.length > 0){
      //   queues.forEach(item => {
      //     data[getGroup[item.group]].queues ++
      //   })
      // }

      // 状态处理
      if(seats.length > 0){
        // console.log('seats:', seats)
        seats.forEach(item => {
          let status
          const group = this._usertel2group(item.username)
          switch(item.status){
            case '1':
              status = 'onlines'
              break
            case '2':
              status = 'busys'
              break
            case '3':
              status = 'exits'
              break
          }
          if(group){
            data[group][status] ++
          }
        })
      }
      // 通话处理
      if(calls.length > 0){
        ['业务组','答疑组','回访组'].forEach(gName =>{
          alltel[gName].forEach(item => {
            let sign = false
            calls.forEach(cItem => {
              if(!Number.isNaN(cItem.caller) && item.usertel == cItem.caller){
                sign = true
              }
            })
            if(sign){
              data[gName].calls ++
            }
          })
        })
      }

      // 计算空闲数
      ['业务组','答疑组','回访组'].forEach(gName => {
        data[gName].frees = alltel[gName].length - data[gName].calls
      })

      // 把data里面的数据与实时监控的数据进行合并
      let rtData = Object.assign([],this.rt.tableData)
      rtData.forEach((rItem,rIndex) =>{
        if(rItem.UserName !== '总分'){
          rtData[rIndex] = Object.assign(rItem,data[rItem.UserName])
        }
      })

      // 添加总分
      let zf = {
        UserName:'总计',
        zcount:0,
        zcount_callin:0,
        zcount_callout:0,
        jtl:0,
        onlines:0,
        frees: 0,
        calls: 0,
        busys: 0,
        exits: 0,
      }
      for(let k in zf){
        if(k !== 'UserName'){
          rtData.forEach(rItem => {
            if(rItem.UserName !== '总计'){
              zf[k] += Number(rItem[k])
            }
          })
        }
      }

      // 总计的接通率做空处理
      zf['jtl'] = ''
      rtData[3] = zf
      this.rt.tableData = rtData
    },
    _is3EmptyArr(cuZRTH) {
      let flag = true
      if (Object.prototype.toString.call(cuZRTH) === '[object Object]') {
        Object.values(cuZRTH).forEach(item => {
          if (item.length > 0) {
            flag = false
          }
        })
      }
      return flag
    },
    _usertel2group(usertel){
      const alltel = this.alltel
      const getGroup = this.getGroup
      let retGroup
      ['业务组','答疑组','回访组'].forEach(gName => {
        alltel[gName].forEach(it => {
          if(it.usertel === usertel){
            retGroup = gName
          }
        })
      })
      return retGroup
    },
    _patchStatus(data){   // 补全状态值
      // 添加总计
      let zf = {
        UserName:'总计',
        zcount:0,
        zcount_callin:0,
        zcount_callout:0,
        jtl:0,
        onlines:0,
        frees: 0,
        calls: 0,
        busys: 0,
        exits: 0,
      }
      data.forEach((item,idx) => {
        zf['zcount'] += Number(item['zcount'])
        zf['zcount_callin'] += Number(item['zcount_callin'])
        zf['zcount_callout'] += Number(item['zcount_callout'])
        zf['jtl'] += Number(item['jtl'])
        data[idx] = Object.assign(item,{
          onlines:0,
          frees: 0,
          calls: 0,
          busys: 0,
          exits: 0,
        })
      })
      // 总计的接通率做空处理
      zf['jtl'] = ''
      data.push(zf)
      return data
    },
    async getAllTel(){
      try{
        const {data} = await this.$get(this,{
          api:'user/getUsertel.do',
        })
        if(data.state === 0){
          this.alltel = data.content
          return
        }
        this.$warn('user/getUsertel响应出错:' + data.message)
      }catch(e){
        console.warn('user/getUsertel:',e.message)
        this.$warn('接口user/getUsertel报错')
      }
    },
    async getJRPB() {  // 获取今日排班信息
      try {
        const { data } = await this.$get(this, {
          api: 'order/selectKFInToday.do',
        })
        if (data.state === 0) {
          this.jrpb = data.content
        }
      } catch (e) {
        this.$warn('系统order/selectKFInToday.do接口报错')
      }
    },
    async getSJJK(){  // 获取实时监控
      try{
        const {data} = await this.$get(this,{
          api:'ajaxapi/zjjk.do',
        })
        if(data.state === 0){
          this.rt.tableData = this._patchStatus(data.content)
        }
      }catch(e){
        console.log('ajaxapi/zjjk.do:', e.message)
        this.$warn('系统接口ajaxapi/zjjk.do报错')
      }
    },
    async getZRTH(gid) {   // 获取昨日通话监控
      try {
        // const { sessionId } = this.$store.getters.getUserInfo
        const { data } = await this.$get(this, {
          api: 'user/indexCall.do',
          data: {
            // sessionId
            groupId:gid
          }
        })
        if (data.state === 0) {
          this.zrth = data.content
        }
      } catch (e) {
        this.$warn('系统user/indexCall.do接口报错')
      }
    },
    async getMyd(adminid) {
      try {
        const { data } = await this.$get(this, {
          api: 'ajaxapi/mydtj.do',
          data: {
            adminid,
            fff: 1
          }
        })
        if (data.state === 0) {
          this.mydData = data.content
        }
      } catch (e) {
        this.$warn('系统ajaxapi/mydtj.do接口报错')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$bdColor: #bac2cb;
.container {
  $color: #444;
  $dftColor: #7b8897;
  .icon {
    &.icon-pb {
      background-image: url(../images/icon-pb.png);
    }
    &.icon-gd {
      background-image: url(../images/icon-gd.png);
    }
    &.icon-th {
      background-image: url(../images/icon-th.jpg);
    }
  }
  table {
    &.content--pb {
      td {
        height: 80px;
        &:first-child {
          color: $dftColor;
        }
      }
      tr:nth-child(2) {
        td {
          color: $color;
        }
      }
      tr:last-child{
        td{
          width:100%;
          overflow-x:auto;
        }
      }
    }
  }
  .subOrderInDay {
    border: none;
    &.unemptyArr{
      min-width:100%;
    }
    td {
      border: none;
      border-right: 1px solid $bdColor;
      &:last-child {
        border-right: none;
      }
    }
  }
}

.scrollContainer {
  overflow-x: auto;
}

.content--zr {
  table {
    min-width: 100%;
    width: auto;
  }
  th:first-child,
  td:first-child {
    width: 200px;
    ul{
      border-right: none;
    }
  }
  ul {
    border-right: 1px solid $bdColor;
  }
  li {
    width: 200px;
    height: 80px;
    // font-size: 12px;
    font-size: 14px;
    border-bottom: 1px solid $bdColor;
    &:last-child {
      border-bottom: none;
    }
    &:after {
      //不使用line-height来防止多行文本影响布局
      display: inline-block;
      content: "";
      width: 0;
      height: 100%;
      vertical-align: middle;
    }
  }
  .empty {
    width: 100%;
    min-width: 200px;
    font-size: 12px;
    text-align: center;
  }
}

.fbox {
  display: flex;
}

.check {
  color: #5394fc;
  border-bottom: 1px solid #5394fc;
  cursor: pointer;
}

// admin昨日通话监控头部样式
.zrjk__top {
    $btmBorderColor: #bac2cb;
    $btnDftBgColor: #ecf0f3;
    $btnDftColor: #bac2cb;
    $btnChgBgColor: #5394fc;
    $btnChgColor: #fff;
    padding: 20px 23px;
    border: 1px solid $btmBorderColor;
    border-bottom: none;
    background: $btnChgColor;
    text-align:right;
    .el-button {
      padding: 11px 29px;
      color: $btnDftColor;
      background: $btnDftBgColor;
      border: none;
      transition:all .3s;
      &:hover {
        color: $btnChgColor;
        background: $btnChgBgColor;
      }
      &.active {
        color: $btnChgColor;
        background: $btnChgBgColor;
      }
    }
  }
</style>
